package com.cloud.bc.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.bc.mapper.BcSinglesMapper;
import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.BcSingles;
import com.cloud.bc.model.entity.BcUsers;
import com.cloud.bc.mapper.BcUsersMapper;
import com.cloud.bc.model.enums.CookieConst;
import com.cloud.bc.service.BcSinglesService;
import com.cloud.bc.service.BcUsersService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.security.AES;
import com.cloud.common.util.CookieUtils;
import com.cloud.common.util.IpUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

/**
 * 用户
 *
 * @author douhaichao code generator
 * @date 2021-01-02 09:06:07
 */
@Service
@AllArgsConstructor
public class BcUsersServiceImpl extends ServiceImpl<BcUsersMapper, BcUsers> implements BcUsersService {

    private final BcSinglesMapper bcSinglesMapper;
//    private final BcSinglesService bcSinglesService;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public BcUsers selectOne(BcUsers req) {
        String pwd = req.getPassword();
        if (StrUtil.isNotEmpty(pwd)) {
            req.setPassword(AES.aesEncrypt(pwd));
        }
        QueryWrapper queryWrapper = new QueryWrapper<BcUsers>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<BcUsers> selectAll(BcUsers req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        String pwd = req.getPassword();
        if (StrUtil.isNotEmpty(pwd)) {
            req.setPassword(AES.aesEncrypt(pwd));
        }
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<BcUsers> selectPage(Page page, BcUsers req) {
        String pwd = req.getPassword();
        if (StrUtil.isNotEmpty(pwd)) {
            req.setPassword(AES.aesEncrypt(pwd));
        }
        IPage<BcUsers> list = baseMapper.selectPage(
                page,
                new QueryWrapper<BcUsers>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<BcUsers> selectPageByLike(Page page, BcUsers req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        String pwd = req.getPassword();
        if (StrUtil.isNotEmpty(pwd)) {
            req.setPassword(AES.aesEncrypt(pwd));
        }
        if (null != req.getId()) {
            queryWrapper.eq("id", req.getId());
        }

        if (!StrUtil.isEmpty(req.getUsername())) {
            queryWrapper.like("username", req.getUsername());
        }

        if (!StrUtil.isEmpty(req.getEmail())) {
            queryWrapper.like("email", req.getEmail());
        }

        if (!StrUtil.isEmpty(req.getPassword())) {
            queryWrapper.like("password", req.getPassword());
        }

        if (null != req.getMobile()) {
            queryWrapper.eq("mobile", req.getMobile());
        }
        if (null != req.getFreeze()) {
            queryWrapper.eq("freeze", req.getFreeze());
        }
        IPage<BcUsers> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(BcUsers req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        String pwd = req.getPassword();
        if (StrUtil.isNotEmpty(pwd)) {
            req.setPassword(AES.aesEncrypt(pwd));
        }
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public UserInfo getUserInfo(HttpServletRequest request) {
//        if (request.getRequestURI().contains("localhost")){
//        UserInfo userInfo = new UserInfo();
//        userInfo.setId(40);
//        userInfo.setEmail("dou631@163.com");
//        userInfo.setUsername("douhaichao");
//        userInfo.setMobile(BigInteger.ZERO);
//        return userInfo;
//        }
        String cookie = CookieUtils.getCookie(request, CookieConst.loginCookie);
        if (StrUtil.isEmpty(cookie)) {
            return null;
        }
        String s = AES.aesDecrypt(cookie);
        return JSONUtil.toBean(s, UserInfo.class);
    }

    @Override
    public void login(HttpServletRequest request, HttpServletResponse response, BcUsers bcUsersResult) {
        //写cookie
        UserInfo userInfo = new UserInfo();
        userInfo.setId(bcUsersResult.getId());
        //通过userId查询用户头象
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", bcUsersResult.getId());
        BcSingles bcSingles = bcSinglesMapper.selectOne(queryWrapper);
        userInfo.setNickname(bcSingles.getNickname());
        userInfo.setPhoto(bcSingles.getPhoto());
        JSONObject jsonObject = JSONUtil.parseObj(userInfo);
        String userStr = jsonObject.toString();
        String userEncode = AES.aesEncrypt(userStr);
        CookieUtils.setCookie(request, response, CookieConst.loginCookie, userEncode);
        //修改最后登录时间
        BcUsers bcUsersUpdateTime = new BcUsers();
        bcUsersUpdateTime.setId(bcUsersResult.getId());
        bcUsersUpdateTime.setLastlogintime(new Date());
        bcUsersUpdateTime.setLastloginip(IpUtils.getIpAddr(request));
        baseMapper.updateById(bcUsersUpdateTime);
    }

    @Override
    public BcUsers loginByMobileEmail(BcUsers bcUsers) {
        String pwd = bcUsers.getPassword();
        if (StrUtil.isNotEmpty(pwd)) {
            bcUsers.setPassword(AES.aesEncrypt(pwd));
        }
        return baseMapper.loginByMobileEmail(bcUsers);
    }
}
